package top.surgeqi.security.demo.config.authenticator;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.surgeqi.security.demo.bean.po.UserAccount;
import top.surgeqi.security.demo.service.UserAccountService;
import top.surgeqi.security.jwt.config.extend.AbstractPrepareExtendAuthenticator;
import top.surgeqi.security.jwt.config.extend.ExtendAuthenticationEntity;
import top.surgeqi.security.jwt.exception.CustomerAuthenticationException;

import javax.annotation.Resource;

/**
 * <p><em>Created by qipp on 2020/5/29 11:28</em></p>
 * 手机号短信验证码认证
 * <blockquote><pre>
 *     注意：目前此示例仅展示手机号短信验证码认证过程，与注册流程无关
 * </pre></blockquote>
 * @author <a href="https://gitee.com/qipengpai">qipp</a>
 * @since 1.0.1
 */
@Component
@Slf4j
public class SmsCodeAuthenticator extends AbstractPrepareExtendAuthenticator {

    /**
     * 手机号短信验证码授权类型
     */
    private final static String AUTH_TYPE = "sms";

    /**
     * 用户账户Service
     */
    @Resource
    private UserAccountService userAccountService;

    /**
     * 根据手机号验证码方式进行认证
     * <p>认证前须判断手机号存在而后再进行验证码验证</p>
     *
     * @param entity 扩展认证实体
     * @return top.surgeqi.security.demo.bean.po.UserAccount
     * @author qipp
     */
    @Override
    public UserDetails authenticate(ExtendAuthenticationEntity entity) {
        // 手机号
        String phone = entity.getAuthParameter("phone");
        // 验证码
        String code = entity.getAuthParameter("code");
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new CustomerAuthenticationException("手机号或验证码为空");
        }

        // 查询用户
        UserAccount userAccount = userAccountService.selectByPhone(phone);
        if (null == userAccount) {
            throw new CustomerAuthenticationException("用户不存在！");
        }

        // todo 验证验证码
        //测试代码块，所以将验证码定为：1234
        if (!"1234".equals(code)) {
            throw new CustomerAuthenticationException("无效的验证码！");
        }
        return this.validateAndComposeUser(userAccount);
    }

    /**
     * 手机号验证码方式
     *
     * @param entity 扩展认证实体
     * @return boolean
     * @author qipp
     */
    @Override
    public boolean support(ExtendAuthenticationEntity entity) {
        return AUTH_TYPE.equals(entity.getAuthType());
    }
}
